package integrationtest;

import connectionpool.ConnectionPool;
import connectionpool.DbTestProperties;
import connectionpool.internal.ConnectionPoolFactory;

/**
 * @author amahmood
 *
 * This class creates multiple threads to get and release connections from
 * connection pool. If there is a synchronization error then you should see "QueueFull"
 * exception in the output. This error can be simulated by removing syncrhonization from
 * connection pool class.
 */
public class ConcurrencyTestApp
{

    /**
     * @param args
     */
    public static void main(String[] args)
    {

        runTest(10, 5);
        runTest(5, 1);
        runTest(5, 2);
        runTest(2, 6);
    }

    /**
     * @param maxThreads
     * @param poolSize
     */
    public  static void runTest(int maxThreads, int poolSize)
    {
        System.out.println("------ Start testConcurrency with threads="+maxThreads+" pool size="+poolSize+"------------");
        
        ConnectionPool connectionPool =  ConnectionPoolFactory.getConnectionPool(poolSize, DbTestProperties.getDefaultProperties());
        
        for (int i = 0; i < maxThreads; i++)
        {
            WorkerThread appThread = new WorkerThread(connectionPool);
            Thread t1 = new Thread(appThread);
            t1.setName("testthread" + i);
            t1.start();

            try
            {
                Thread.sleep(RandomNumberUtil.nextInt(1000));
            }
            catch (InterruptedException e)
            {
                System.err.println("Some thing to worry about. " + e.getMessage() + " " + e);
            }
        }
        System.out.println("------ End testConcurrency with threads="+maxThreads+" pool size="+poolSize+"------------");
    }
    
}
